<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>防抖和节流</title>
    <style>
        body {
            height: 60000px;
        }
    </style>
</head>

<body>
    <input type="text" placeholder="防抖">
    <script>
        let input = document.querySelector('input');
        input.oninput = dobe(function() {
                console.log(this.value)
            }, 500)
            // 防抖
        function dobe(fn, delay) {
            let time = null;
            return function() {
                if (time !== null) {
                    clearTimeout(time);
                }
                time = setTimeout(() => {
                    fn.apply(this)
                }, delay)
            }
        }

        // 节流
        window.onscroll = throttle(function() {
            console.log('节流')
        }, 2000)

        function throttle(fn, delay) {
            let flag = true;
            return function() {
                if (flag) {
                    setTimeout(() => {
                        fn.apply(this);
                        flag = true;
                    }, delay)
                }
                flag = false
            }
        }
    </script>
</body>

</html>